<template>
    <el-container class="chat-layout">
        <!-- Sidebar with conversation history -->
        <el-aside width="300px" class="sidebar">
            <div class="sidebar-header">
                <el-avatar :size="40" src="https://placekitten.com/g/200/200" />
                <h2>ChatGPT</h2>
            </div>
            <el-input
                v-model="searchQuery"
                placeholder="搜索对话"
                prefix-icon="el-icon-search"
                clearable
                class="search-input"
            />
            <el-scrollbar height="calc(100vh - 140px)">
                <el-menu class="conversation-list" :default-active="activeConversation">
                    <el-sub-menu v-for="(conversations, date) in groupedConversations" :key="date" :index="date">
                        <template #title>
                            <span>{{ formatDate(date) }}</span>
                        </template>
                        <el-menu-item
                            v-for="conv in conversations"
                            :key="conv.id"
                            :index="conv.id.toString()"
                            @click="loadConversation(conv)"
                        >
                            <el-tooltip :content="conv.title" placement="right" :show-after="1000">
                                <span>{{ truncate(conv.title) }}</span>
                            </el-tooltip>
                        </el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </el-scrollbar>
        </el-aside>

        <!-- Main chat area -->
        <el-container class="chat-area">
            <el-header class="chat-header">
                <h1>{{ currentConversation ? currentConversation.title : '新对话' }}</h1>
                <el-button-group>
                    <el-button icon="el-icon-delete" @click="clearChat"  >清空对话</el-button>
                    <el-button icon="el-icon-upload2" @click="exportChat" >导出对话</el-button>
                </el-button-group>
            </el-header>

            <!-- Chat window -->
            <el-main class="chat-window" ref="chatWindow">
                <el-scrollbar height="100%">
                    <transition-group name="fade">
                        <div v-for="(msg, index) in messages" :key="index" class="message-container" :class="{ 'user-message': msg.isUser }">
                            <el-card class="message" shadow="hover">
                                <template #header>
                                    <div class="message-avatar">
                                        <el-avatar :icon="msg.isUser ? 'el-icon-user' : 'el-icon-chat-dot-round'" :size="24" :class="msg.isUser ? 'user-avatar' : 'bot-avatar'" />
                                    </div>
                                </template>
                                <div class="message-content">
                                    <p>{{ msg.text }}</p>
                                </div>
                            </el-card>
                        </div>
                    </transition-group>
                </el-scrollbar>
            </el-main>

            <!-- Input area -->
            <el-footer class="chat-input">
                <el-input
                    v-model="userInput"
                    type="textarea"
                    :rows="1"
                    autosize
                    placeholder="输入您的消息..."
                    @keyup.enter.native.prevent="sendMessage"
                >
                    <template #append>
                        <el-button type="primary" icon="el-icon-s-promotion" @click="sendMessage" :disabled="!userInput.trim()">
                            发送
                        </el-button>
                    </template>
                </el-input>
            </el-footer>
        </el-container>
    </el-container>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { ElNotification, ElMessageBox } from 'element-plus';
import WebSocketService from '../ws/websocketService.js'; // 引入 WebSocket 服务

const messages = ref([{ text: '欢迎来到ChatGPT！请问有什么可以帮助您的？', isUser: false }]);
const userInput = ref('');
const chatWindow = ref(null);
const searchQuery = ref('');
const activeConversation = ref('');
const currentConversation = ref(null);
let webSocketService = null;
let activeResponse = ref("");  // 用于逐步显示接收的消息内容

// Simulated conversation history
const conversations = ref([
    { id: 1, title: '关于人工智能的讨论', date: '2023-05-15', messages: [] },
    { id: 2, title: '编程语言比较', date: '2023-05-15', messages: [] },
    { id: 3, title: '机器学习模型训练', date: '2023-05-14', messages: [] },
    { id: 4, title: '数据结构和算法', date: '2023-05-13', messages: [] },
]);

const groupedConversations = computed(() => {
    return conversations.value.reduce((acc, conv) => {
        if (!acc[conv.date]) acc[conv.date] = [];
        acc[conv.date].push(conv);
        return acc;
    }, {});
});

// 发送消息
const sendMessage = async () => {
    if (!userInput.value.trim()) return;

    messages.value.push({ text: userInput.value, isUser: true });
    const messageToSend = userInput.value;
    userInput.value = '';

    await nextTick(); // 确保 DOM 更新
    scrollToBottom();  // 滚动到底部

    // 发送消息到 WebSocket
    webSocketService.sendMessage(messageToSend);
};

// 处理接收到的消息，逐步显示内容
const handleIncomingMessage = (rawMessage) => {
    let data;
    try {
        data = JSON.parse(rawMessage.replace(/^data: /, ''));
    } catch (error) {
        console.error("Failed to parse message:", error);
        return;
    }

    // 检查是否为消息的一个部分，并逐步添加
    if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
        activeResponse.value += data.choices[0].delta.content;

        // 如果消息列表为空或最后一条是用户消息，创建新的 AI 消息
        if (!messages.value.length || messages.value[messages.value.length - 1].isUser) {
            messages.value.push({ text: activeResponse.value, isUser: false });
        } else {
            // 更新当前 AI 消息的内容
            messages.value[messages.value.length - 1].text = activeResponse.value;
        }
        scrollToBottom();
    }

    // 检查是否包含 `usage` 字段，表示对话结束
    if (data.usage) {
        activeResponse.value = "";  // 重置，准备接收下一条消息
    }
};

// 滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (chatWindow.value) {
            const scrollbar = chatWindow.value.$el.querySelector('.el-scrollbar__wrap');
            if (scrollbar) {
                scrollbar.scrollTop = scrollbar.scrollHeight;
            }
        }
    });
};

const loadConversation = (conversation) => {
    currentConversation.value = conversation;
    activeConversation.value = conversation.id.toString();
    ElNotification({
        title: '加载对话',
        message: `正在加载对话: ${conversation.title}`,
        type: 'info',
        position: 'top-right'
    });
};

const clearChat = () => {
    ElMessageBox.confirm('确定要清空当前对话吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        messages.value = [];
        ElNotification({
            title: '清空对话',
            message: '对话已清空',
            type: 'success'
        });
    }).catch(() => {});
};

const exportChat = () => {
    const chatContent = messages.value.map(msg => `${msg.isUser ? 'User' : 'AI'}: ${msg.text}`).join('\n');
    const blob = new Blob([chatContent], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'chat_export.txt';
    a.click();
    URL.revokeObjectURL(url);
    ElNotification({
        title: '导出对话',
        message: '对话已成功导出',
        type: 'success'
    });
};

const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
};

const truncate = (str, length = 20) => str.length > length ? str.substring(0, length) + '...' : str;

onMounted(() => {
    // 创建 WebSocket 服务实例
    webSocketService = new WebSocketService('ws://localhost:21800/ws/chat');
    webSocketService.connect();

    // 添加消息监听器
    webSocketService.addMessageListener(handleIncomingMessage);

    scrollToBottom();
});

onBeforeUnmount(() => {
    if (webSocketService) {
        webSocketService.disconnect();
    }
});
</script>

<style scoped>
.chat-layout {
    height: 100vh;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: var(--el-box-shadow-light);
    background-color: var(--el-bg-color);
}

.sidebar {
    background-color: var(--el-bg-color-page);
    border-right: 1px solid var(--el-border-color-light);
    display: flex;
    flex-direction: column;
}

.sidebar-header {
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    border-bottom: 1px solid var(--el-border-color-light);
}

.sidebar-header h2 {
    margin: 0;
    font-size: 1.2rem;
    color: var(--el-text-color-primary);
}

.search-input {
    margin: 10px;
    width: calc(100% - 20px);
}

.conversation-list {
    border-right: none;
}

.chat-area {
    display: flex;
    flex-direction: column;
}

.chat-header {
    background-color: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-light);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
}

.chat-header h1 {
    font-size: 1.2rem;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0;
}

.chat-window {
    flex: 1;
    padding: 1rem;
    background-color: var(--el-bg-color-page);
    overflow: hidden;
}

.message-container {
    margin-bottom: 1rem;
    display: flex;
    align-items: flex-start;
}

.message {
    max-width: 70%;
    border-radius: 8px;
    padding: 10px;
    box-shadow: var(--el-box-shadow-light);
    font-size: 0.9rem; /* 减小文字大小 */
}

.user-message {
    justify-content: flex-end;
}

.user-message .message {
    background-color: var(--el-color-primary-light-9);
    color: var(--el-text-color-primary);
}

.message-avatar {
    margin-right: 10px;
}

.user-avatar {
    background-color: var(--el-color-primary);
    color: white;
}

.bot-avatar {
    background-color: var(--el-color-success);
    color: white;
}

.message-content {
    margin-top: 0.5rem;
    font-size: 0.9rem; /* 减小文字大小 */
}

.chat-input {
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-light);
    padding: 10px;
}

.fade-enter-active,
.fade-leave-active {
    transition: all 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    transform: translateY(20px);
}
</style>